package cn.com.gzheroli.core.util;

import java.beans.BeanInfo;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.beanutils.PropertyUtils;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * @author  张代浩
 * @version 1.0
 */

public class MyBeanUtils
    extends org.apache.commons.beanutils.BeanUtils {

  private static void convert(Object dest, Object orig) throws
      IllegalAccessException, InvocationTargetException {

      // Validate existence of the specified beans
      if (dest == null) {
          throw new IllegalArgumentException
              ("No destination bean specified");
      }
      if (orig == null) {
          throw new IllegalArgumentException("No origin bean specified");
      }

      // Copy the properties, converting as necessary
      if (orig instanceof DynaBean) {
          DynaProperty origDescriptors[] =
              ( (DynaBean) orig).getDynaClass().getDynaProperties();
          for (int i = 0; i < origDescriptors.length; i++) {
              String name = origDescriptors[i].getName();
              if (PropertyUtils.isWriteable(dest, name)) {
                  Object value = ( (DynaBean) orig).get(name);
                  try {
                      copyProperty(dest, name, value);
                  }
                  catch (Exception e) {
                      ; // Should not happen
                  }

              }
          }
      }
      else if (orig instanceof Map) {
          Iterator names = ( (Map) orig).keySet().iterator();
          while (names.hasNext()) {
              String name = (String) names.next();
              if (PropertyUtils.isWriteable(dest, name)) {
                  Object value = ( (Map) orig).get(name);
                  try {
                      copyProperty(dest, name, value);
                  }
                  catch (Exception e) {
                      ; // Should not happen
                  }

              }
          }
      }
      else
      /* if (orig is a standard JavaBean) */
      {
          PropertyDescriptor origDescriptors[] =
              PropertyUtils.getPropertyDescriptors(orig);
          for (int i = 0; i < origDescriptors.length; i++) {
              String name = origDescriptors[i].getName();
//              String type = origDescriptors[i].getPropertyType().toString();
              if ("class".equals(name)) {
                  continue; // No point in trying to set an object's class
              }
              if (PropertyUtils.isReadable(orig, name) &&
                  PropertyUtils.isWriteable(dest, name)) {
                  try {
                      Object value = PropertyUtils.getSimpleProperty(orig, name);
                      copyProperty(dest, name, value);
                  }
                  catch (java.lang.IllegalArgumentException ie) {
                      ; // Should not happen
                  }
                  catch (Exception e) {
                      ; // Should not happen
                  }

              }
          }
      }

  }

  
  /**
	 * 对象拷贝
	 * 数据对象空值不拷贝到目标对象
	 * 
	 * @param dataObject
	 * @param toObject
	 * @throws NoSuchMethodException
	 * copy
	 */
  public static void copyBeanNotNull2Bean(Object databean,Object tobean)throws Exception
  {
	  PropertyDescriptor origDescriptors[] =
          PropertyUtils.getPropertyDescriptors(databean);
      for (int i = 0; i < origDescriptors.length; i++) {
          String name = origDescriptors[i].getName();
//          String type = origDescriptors[i].getPropertyType().toString();
          if ("class".equals(name)) {
              continue; // No point in trying to set an object's class
          }
          if (PropertyUtils.isReadable(databean, name) &&
              PropertyUtils.isWriteable(tobean, name)) {
              try {
                  Object value = PropertyUtils.getSimpleProperty(databean, name);
                  if(value!=null){
                	    copyProperty(tobean, name, value);
                  }
              }
              catch (java.lang.IllegalArgumentException ie) {
                  ; // Should not happen
              }
              catch (Exception e) {
                  ; // Should not happen
              }

          }
      }
  }
  
  
  /**
   * 把orig和dest相同属性的value复制到dest中
   * @param dest
   * @param orig
   * @throws IllegalAccessException
   * @throws InvocationTargetException
   */
  public static void copyBean2Bean(Object dest, Object orig) throws Exception {
      convert(dest, orig);
  }

  public static void copyBean2Map(Map map, Object bean){
	PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean);
	for (int i =0;i<pds.length;i++)
	{
		PropertyDescriptor pd = pds[i];
		String propname = pd.getName();
		try {
			Object propvalue = PropertyUtils.getSimpleProperty(bean,propname);
			map.put(propname, propvalue);
		} catch (IllegalAccessException e) {
			//e.printStackTrace();
		} catch (InvocationTargetException e) {
			//e.printStackTrace();
		} catch (NoSuchMethodException e) {
			//e.printStackTrace();
		}
	}
  }

  /**
   * 将Map内的key与Bean中属性相同的内容复制到BEAN中
   * @param bean Object
   * @param properties Map
   * @throws IllegalAccessException
   * @throws InvocationTargetException
   */
  public static void copyMap2Bean(Object bean, Map properties) throws
      IllegalAccessException, InvocationTargetException {
      // Do nothing unless both arguments have been specified
      if ( (bean == null) || (properties == null)) {
          return;
      }
      // Loop through the property name/value pairs to be set
      Iterator names = properties.keySet().iterator();
      while (names.hasNext()) {
          String name = (String) names.next();
          // Identify the property name and value(s) to be assigned
          if (name == null) {
              continue;
          }
          String key=NameUtils.underscore2camel(name);
          Object value = properties.get(name);
              String typeName="";  
        	  typeName=getFieldTypeName(bean.getClass(),key);
        	  if(typeName.equals(""))
        		  continue;
              if(typeName.equalsIgnoreCase("java.util.Date")||typeName.equalsIgnoreCase("java.sql.Timestamp"))
	        	  value=convertTimeDate(typeName,value);
              setProperty(bean, name, value);
      }
  }
  public static Object convertTimeDate(String typeName,Object value){
	  if (typeName.equalsIgnoreCase("java.util.Date")) {
    	  Timestamp timestamp =getDateColumn(value); 
    	  if(timestamp!=null) 
    		  value = new java.util.Date((timestamp).getTime()); 
		  else 
			  value=null; 
    	  
      }else if (typeName.equalsIgnoreCase("java.sql.Timestamp")){
    	  value = getDateColumn(value);
      }
	  return value;
  }
  public static String getFieldTypeName(Class entityName,String key){
	  String typeName="";
	  try{
		  Field f = entityName.getDeclaredField(key);
          if (null == f) {	// 在bean中这个属性不存在
              return "";
          }
          typeName=f.getType().getName();
      } catch (NoSuchFieldException e) {
			try {
				Field f = entityName.getField(key);
				if (null == f) { // 在bean中这个属性不存在
					return "";
				}
				typeName = f.getType().getName();
			} catch (NoSuchFieldException e1) {
				return "";
			} catch (SecurityException e1) {
				return "";
			} 
	  }
	  return typeName;
  }
  /**
   * 自动转Map key值大写
   * 将Map内的key与Bean中属性相同的内容复制到BEAN中
   * @param bean Object
   * @param properties Map
   * @throws IllegalAccessException
   * @throws InvocationTargetException
   */
  public static <T> T copyMap2Bean_Dozer(Class entityName, Map properties) {
      // Do nothing unless both arguments have been specified
      if ((properties == null)) {
          return null;
      }
      Map map=new HashMap();
      // Loop through the property name/value pairs to be set
      Iterator names = properties.keySet().iterator();
      while (names.hasNext()) {
          String name = (String) names.next();
          // Identify the property name and value(s) to be assigned
          if (name == null) {
              continue;
          }
          String key=NameUtils.underscore2camel(name);
          Object value = properties.get(name);
          try {
	          if (value == null) {	// 不光Date类型，好多类型在null时会出错
	              continue;	// 如果为null不用设 (对象如果有特殊初始值也可以保留？)
	          }
	          String typeName="";
        	  
        	  typeName=getFieldTypeName(entityName,key);
        	  if(typeName.equals(""))
        		  continue;
	          if(typeName.equalsIgnoreCase("java.util.Date")||typeName.equalsIgnoreCase("java.sql.Timestamp"))
	        	  value=convertTimeDate(typeName,value);
	          map.put(key, value);
	      }  catch (SecurityException e) {
			continue;
		}
         
      }
      return (T)BeanMapper.mapToBean(map, entityName);
  }

  /**
   * 自动转Map key值大写
   * 将Map内的key与Bean中属性相同的内容复制到BEAN中
   * @param bean Object
   * @param properties Map
   * @throws IllegalAccessException
   * @throws InvocationTargetException
   */
  public static void copyMap2Bean_Nobig(Object bean, Map properties) throws
      IllegalAccessException, InvocationTargetException {
      // Do nothing unless both arguments have been specified
      if ( (bean == null) || (properties == null)) {
          return;
      }
      // Loop through the property name/value pairs to be set
      Iterator names = properties.keySet().iterator();
      while (names.hasNext()) {
          String name = (String) names.next();
          // Identify the property name and value(s) to be assigned
          if (name == null) {
              continue;
          }
          Object value = properties.get(name);
          String key=NameUtils.underscore2camel(name);
          // 命名应该大小写应该敏感(否则取不到对象的属性)
          //name = name.toLowerCase();
          try {
        	  if (value == null) {	// 不光Date类型，好多类型在null时会出错
	              continue;	// 如果为null不用设 (对象如果有特殊初始值也可以保留？)
	          }
        	  String typeName="";
        	  typeName=getFieldTypeName(bean.getClass(),key);
        	  if(typeName.equals(""))
        		  continue;
        	  if(typeName.equalsIgnoreCase("java.util.Date")||typeName.equalsIgnoreCase("java.sql.Timestamp"))
	        	  value=convertTimeDate(typeName,value);
              setProperty(bean, name, value);
          } catch (SecurityException e) {
  			continue;
  		}
      }
  }

  /**
   * Map内的key与Bean中属性相同的内容复制到BEAN中
   * 对于存在空值的取默认值
   * @param bean Object
   * @param properties Map
   * @param defaultValue String
   * @throws IllegalAccessException
   * @throws InvocationTargetException
   */
  public static void copyMap2Bean(Object bean, Map properties, String defaultValue) throws
      IllegalAccessException, InvocationTargetException {
      // Do nothing unless both arguments have been specified
      if ( (bean == null) || (properties == null)) {
          return;
      }
      // Loop through the property name/value pairs to be set
      Iterator names = properties.keySet().iterator();
      while (names.hasNext()) {
          String name = (String) names.next();
          // Identify the property name and value(s) to be assigned
          if (name == null) {
              continue;
          }
          Object value = properties.get(name);
          String key=NameUtils.underscore2camel(name);
          try {
        	  if (value == null) {	// 不光Date类型，好多类型在null时会出错
	              continue;	// 如果为null不用设 (对象如果有特殊初始值也可以保留？)
	          }
	         // Field f = bean.getClass().getDeclaredField(key);
        	  String typeName="";
        	  typeName=getFieldTypeName(bean.getClass(),key);
        	  if(typeName.equals(""))
        		  continue;
        	  if(typeName.equalsIgnoreCase("java.util.Date")||typeName.equalsIgnoreCase("java.sql.Timestamp"))
	        	  value=convertTimeDate(typeName,value);
              setProperty(bean, name, value);
          }  catch (SecurityException e) {
  			continue;
  		}
      }
  }
  
  public MyBeanUtils() {
    super();
  }

	/** 
   * @reference oracle.sql.Datum.timestampValue(); 
   * @return 
   */ 
	public static Timestamp getOracleTimestamp(Object value) { 
		try { 
			Class clz = value.getClass(); 
			Method m = clz.getMethod("timestampValue", null); 
			                     //m = clz.getMethod("timeValue", null); 时间类型 
			                     //m = clz.getMethod("dateValue", null); 日期类型 
			return (Timestamp) m.invoke(value, null); 
		} catch (Exception e) { 
			return null; 
		} 
	}
	public static Timestamp getDateColumn(Object value){
		Timestamp timestamp=null;
		try { 
  		  timestamp = (Timestamp) value; 
  	  } catch (Exception e) { 
  		  timestamp = getOracleTimestamp(value); 
  	  }
		return timestamp;
	}
}
